<?php
namespace app\admin\controller;
use tools\Tools;//自定义类
use app\common\controller\Base as  CommonBase;
use think\Session;
use think\Config;
use think\Request;
use think\Db;
use app\admin\model\Admin;
class Login extends CommonBase
{
    /*
     *登录
     */
    public function index () {
       if(Session::get('admin_id')){
            $this->redirect('Index/index');
        }else{
            return $this->fetch();
        }
    }

    /**
     *验证码
     *
     */
    public function get_captcha(){    
        //使用memcheck 设置session    
        Session::init(['prefix'=> 'wll_','type'=> '','auto_start' => true]);
        $captcha = new \other\Captcha(86,48,4);
        echo $captcha->showImg();        
        Session::set('code',$captcha->getCaptcha());
        exit;    
    } 
    /*
     *登录操作
     *
     */
    public function doLogin() {
        $admin_module = new Admin;
        $request = Request::instance();
        $username = $request->param('username');
        $password = $request->param('password');
        $code = $request->param('code');
        if($code != Session::get('code','wll_')) {
            return json(['error'=>0,'error_msg'=>'验证码不正确！']); 
        }
        $hasUser = db('admin')->where('username', $username)->find();
        if(!$hasUser) {
            return json(['error'=>0,'error_msg'=>'管理员不存在！']);
        } 
        if(md5($password) != $hasUser['password']){
            return json(['error'=>0,'error_msg'=>'密码不正确！']);
        } 
        if(1 != $hasUser['status']) {
           return json(['error'=>0,'error_msg'=>'帐号已被禁止！']);
        }
        if($hasUser['isonline'] == 1) {
            return json(['error'=>0,'error_msg'=>'该帐号已在另一台设备登录!']);
        }
        // 写入数据
        Db::startTrans();
        try{
            $data = [
                'currentlogin'  => time(),
                'lastlogin'     => $hasUser['currentlogin'],
                'curentip'     => $this->request->ip(),
                'lastip'        => $hasUser['curentip'],
                'isonline'      => 1
            ];
            Db::name('admin')->where('id',$hasUser['id'])->update($data);
            $admin_module->log($hasUser['id'],'登录成功！');
            // 提交事务
            Db::commit();    
            Session::set('admin_id',$hasUser['id']);
            return json(['error'=>1,'error_msg'=>'登录成功！']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json (['error'=>0,'error_mg'=>'登录失败！']);
        }
    }

    /**
     *登出
     *
     */
    public function logout() {
        $admin_id = Session::pull('admin_id');
        if($admin_id){ 
            $admin_module = new Admin;
            $admin_module->log($admin_id,'已退出登录！');
        }
        $this->redirect('Login/index');
    }
} 
